"use strict";

const Package = require("@liusion-cli-dev/package");
const path = require("path");
const SETTINGS = {
  init: "@liusion-cli-dev/init",
};

// const CACHE_DIR = "dependencies";
const CACHE_DIR = "/AppData/Roaming/npm";
function exec() {
  //   console.log("exec arguments", arguments);
  let targetPath = process.env.CLI_TARGET_PATH;
  let storeDir = "";
  let pkg;
  const homePath = process.env.CLI_HOME_PATH;
  const cmdObj = arguments[arguments.length - 1];
  const cmdName = cmdObj.name();
  const packageName = SETTINGS[cmdName];
  const packageVersion = "latest";

  if (!targetPath) {
    //生成缓存路径
    targetPath = path.resolve(homePath, CACHE_DIR);
    storeDir = path.resolve(targetPath, "node_modules");
    // C:\\Users\\28356\\AppData\\Local\\npm-cache
    console.log("targetPath storeDir", targetPath, storeDir);
    pkg = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion,
    });

    if (pkg.exists()) {
      //更新package
    } else {
      //安装package
      pkg.install();
    }
  } else {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
    });
  }

  const rootFile = pkg.getRootFilePath();
  console.log("rootFile", rootFile);
  require(rootFile).apply(null, arguments);
}

module.exports = exec;
